'use client'
import React, { useRef, useState, useEffect, useCallback } from 'react'
import PageTitle from '@/components/admin/common/PageTitle'
import axios from 'axios'
import 'nprogress/nprogress.css'
import NProgress from 'nprogress'
import message from '@/components/common/message'
import Image from 'next/image'
import Loading from '@/components/common/Loading'
import { Trash2, Link2 } from 'lucide-react'
import Pagination from '@/components/admin/common/Pagination'
import IconButton from '@/components/common/IconButton'

const isVideo = (url) => /\.(mp4|webm|ogg|mov|avi|mkv)$/i.test(url);

export default function Page() {
  const [files, setFiles] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 12;
  const fileInputRef = useRef();
  const [loaded, setLoaded] = useState(false);

  const fetchFiles = useCallback(async (curPage = page) => {
    setLoaded(false);
    let data = null;
    const res = await fetch(`/api/admin/files?page=${curPage}&pageSize=${pageSize}`, { method: 'GET', credentials: 'include' });
    try {
      data = await res.json();
    } catch {
      message.error('获取文件列表失败，请稍后再试！');
      setLoaded(true);
      return;
    }
    setFiles(data.files || []);
    setTotal(data.total || 0);
    setLoaded(true);
  }, [page, pageSize]);

  useEffect(() => {
    fetchFiles(page);
  }, [page, fetchFiles]);

  const handleUpload = (e) => {
    const files = Array.from(e.target.files).slice(0, 12);
    if (files.length === 0) return;
    let uploadedCount = 0;
    NProgress.start();
    files.forEach(file => {
      const formData = new FormData();
      formData.append('file', file);
      axios.post('/api/admin/files', formData, {
        onUploadProgress: (event) => {
          if (event.total) {
            const percent = Math.round((event.loaded / event.total) * 100);
            NProgress.set(percent / 100);
          }
        }
      }).then(res => {
        if (res.data.code === 0) {
          if (++uploadedCount === files.length) {
            message.success('全部上传成功！');
            NProgress.done();
            fetchFiles(1);
            setPage(1);
          }
        } else {
          message.error(res.data.codeMap[res.data.code] || '上传失败');
          NProgress.done();
        }
        if (uploadedCount === files.length) fileInputRef.current.value = '';
      }).catch(() => {
        message.error('上传失败');
        NProgress.done();
        if (uploadedCount === files.length) fileInputRef.current.value = '';
      });
    });
  };

  const handleCopy = (url) => {
    const origin = window.location.origin;
    const fullUrl = origin + url;
    navigator.clipboard.writeText(fullUrl);
    message.success('复制成功！');
  };

  const handleRight = () => {
    fileInputRef.current.click();
  };

  const totalPages = Math.ceil(total / pageSize);

  const handleDelete = async (url) => {
    const filename = url.split('/').pop();
    if (!filename) return;
    if (!window.confirm('确定要删除该文件吗？')) return;
    const res = await fetch('/api/admin/files', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename }), });
    const data = await res.json();
    if (data.code === 0) {
      message.success(data.codeMap[data.code] || '删除成功');
      fetchFiles(page);
    } else {
      message.error(data.codeMap[data.code] || '删除失败');
    }
  };

  const content = (
    <div>
      <PageTitle title={'文件管理'} buttonText={'上传'} onButtonClick={handleRight} />
      <input type="file" accept="image/*,video/*" multiple ref={fileInputRef} style={{ display: 'none' }} onChange={handleUpload} />
      <div className="flex flex-col mt-2 box-border rounded-sm bg-white">
        <div className='flex items-center justify-between px-2 border-b-1 border-b-gray-200 py-3 font-semibold'>
          <div className="text-xs flex-2 text-[#333333]"><span className='pl-12'>文件名</span></div>
          <div className="text-xs flex-1 text-[#333333]">大小</div>
          <div className="text-xs flex-1 text-[#333333]">上传时间</div>
          <div className="text-xs flex-1 text-[#333333] text-right"><span className=' pr-8'>操作</span></div>
        </div>
        {files.map(({url, type, size, created_at}, idx) => {
          return (
            <div key={url + idx} className="relative rounded-xs bg-white px-2 py-2 flex items-center justify-between border-b-1 border-b-gray-200">
              <div className='flex flex-2 gap-2 items-center'>
                <div className='w-10 aspect-square overflow-hidden rounded-sm border-1 border-gray-200'>
                  {isVideo(url) ? (
                    <video src={url} controls={false} className="w-full h-full object-cover rounded bg-black" preload="metadata" poster="" loading="lazy" onClick={e => e.currentTarget.controls = true} tabIndex={0} > 您的浏览器不支持 video 标签。 </video>
                  ) : (
                    <Image src={url} alt="uploaded" width={720} height={720} sizes="100vw" priority={true} className="w-full h-full object-cover" />
                  )}
                </div>
                <div>
                  <div className="text-xs text-[#333333]">{url.split('/').pop()}</div>
                  <div className="text-xs text-[#666666] truncate font-medium">{type}</div>
                </div>
              </div>
              <div className='text-xs flex-1 text-left text-[#666666]'>{size}</div>
              <div className='text-xs flex-1 text-left text-[#666666]'>{created_at}</div>
              <div className="flex flex-1 gap-2 justify-end">
                <IconButton onClick={() => handleCopy(url)} ><Link2 color="#ffffff" /></IconButton>
                <IconButton onClick={() => handleDelete(url)} className={'bg-red-500'}><Trash2 color="#ffffff" /> </IconButton>
              </div>
            </div>
          );
        })}
      </div>
      <Pagination total={total} page={page} limit={pageSize} leftDisabled={page === 1} rightDisabled={page === totalPages || totalPages === 0} leftOnClick={() => setPage(page - 1)} rightOnClick={() => setPage(page + 1)} />
    </div>
  )
  return (
    <>{loaded ? content : <Loading />}</>
  );
}